import React, { useRef, useEffect, useState, useMemo } from 'react';
import { Form, Input, Checkbox, Select } from 'antd';
import {
  modalRefArg,
  ModalWrapper,
  DrawerWrapper,
  submitFunction,
  onShowFunction
} from '@/components/antd/modal';
import CSelect from '@/components/antd/select';
import AgGroup from '@/components/antd/group';
import { randomNumber } from '@/utils';

interface modalRef {
  id: number;
  name: string
}

interface Ilist {
  name?: string;
  alias?: string;
  code?: number | string;
  select?: any;
  dis: boolean,
  cc?: any
}
const list: Array<Ilist> = [
  { name: '你好', alias: 'aaa', code: 111, select: [111], dis: true, },
  { name: '你好666', alias: 'bbb', code: 222, select: [222], dis: false },
  { name: '钟琪钰', alias: 'ccc', code: 333, select: [111], dis: false },
  { name: '曦曦', alias: 'ddd', code: 444, select: [111], dis: true },
  { name: '色伟', alias: 'eee', code: 555, select: [111], dis: true },
]

const Demo = (props: any) => {
  const { forwardParams, form } = props;

  const [listData, setListData] = useState<Array<Ilist>>([]);

  const newList: any = useMemo(() => {
    const arr = new Array(5).fill(0).map((item, index) => {
      const a = Math.random().toFixed(3)
      return {
        name: `你好 ${index}`,
        alias: `aaa ${a}`,
        code: index,
        select: [111],
      }
    })

    return arr
  }, [])

  useEffect(() => {
    setTimeout(() => {
      setListData(newList)
    }, 1000)
  }, [])

  console.log('###:  渲染--------------',);
  return (
    <React.Fragment>
      <Form form={form}>
        <Form.Item
          name='ddd'
          label='测试'
        >
          <CSelect
            mode='multiple'
            dataSource={list}
          />
        </Form.Item>
      </Form>

      <button onClick={() => {
        console.log('###:  ', form.getFieldsValue());
      }}>表单</button>



      <AgGroup
        style={{
          width: 600
        }}
        initValue={{
          name: '测试',
          code: 111,
          select: [111],
          dis: true
        }}
        // keyName='code'
        // min={3}
        dataSource={listData}
        render={(target, id, fun) => {
          return (
            <div style={{
              display: 'flex',
              width: '100%',
              justifyContent: 'space-around',
            }}>
              <div style={{ margin: '5px' }} >
                <Input
                  value={target.name}
                  onChange={(e) => {
                    fun.notify(id, (item) => {
                      item.name = e.target.value
                    })
                  }}
                />
              </div>
              <div style={{ margin: '5px' }} >
                <Input
                  value={target.alias}
                  onChange={(e) => {
                    fun.notify(id, (item) => {
                      item.alias = e.target.value
                    })
                  }}
                />
              </div>
              <div style={{ margin: '5px' }} >
                <CSelect
                  mode='multiple'
                  value={target.select}
                  dataSource={list}
                  onChange={() => { }}
                  handleChange={(value: any) => {
                    fun.notify(id, (item) => {
                      item.select = value
                      item.alias = value
                    })
                  }}
                />
              </div>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  paddingBottom: 5,
                  width: 150,
                  height: 50
                }}
              >
                <button
                  onClick={() => {
                    fun.add(id)
                  }}
                >新增</button>
                <button
                  onClick={() => {
                    fun.remove(id)
                  }}
                >删除</button>
                <button
                  onClick={() => {
                    fun.copy(id)
                  }}
                >复制</button>
              </div>
            </div>
          );
        }}
        getProcessedData={(data: any) => {
          forwardParams && forwardParams(data)
        }}
      >
        <div>规则条件</div>
        <div>审批人</div>
        <div>抄送人</div>
        <div></div>
      </AgGroup>
    </React.Fragment>
  )
}



const App: React.FC = () => {
  const modalRef = useRef<modalRefArg<'modal', modalRef> | null>(null)

  const drawerRef = useRef<modalRefArg<'drawer', modalRef> | null>(null)


  const a = 15626

  const submit: submitFunction<modalRef> = (a, b) => {

    console.log('###:  ', a, b);
    return new Promise((resolve, reject) => {
      // resolve(1111)


      return true
    })
  }

  const onShow: onShowFunction<modalRef, 'drawer'> = (a, b, c) => {
    console.log('###:  ', a.id, b, b.title);
  }


  const datalist: Array<Ilist> = [
    { name: '你好', alias: 'aaa', code: 111, select: [111], dis: true, },
    { name: '你好666', alias: 'bbb', code: 222, select: [222], dis: false },
    { name: '钟琪钰', alias: 'ccc', code: 333, select: [111], dis: false },
    { name: '曦曦', alias: 'ddd', code: 444, select: [111], dis: true },
    { name: '色伟', alias: 'eee', code: 555, select: [111], dis: true },
  ]

  const creactList = (searchValue: any) => {
    if (!searchValue) return list;

    const newList: Array<Ilist> = [
      { name: `凌泳${randomNumber(0, 100)}`, code: randomNumber(60, 70), select: 111, dis: true },
      { name: `琪钰${randomNumber(0, 100)}`, code: randomNumber(70, 80), select: 111, dis: false },
      { name: `骚炮${randomNumber(0, 100)}`, code: randomNumber(80, 90), select: 111, dis: false },
      { name: `曦曦${randomNumber(0, 100)}`, code: randomNumber(90, 100), select: 111, dis: true },
      { name: `色伟${randomNumber(0, 100)}`, code: randomNumber(100, 110), select: 111, dis: true },
    ]

    return newList.slice(0, randomNumber(2, 5))
  }


  const list: Array<Ilist> = [
    { name: '你好', alias: 'aaa', code: 111, select: [111], dis: true, },
    { name: '你好666', alias: 'bbb', code: 222, select: [222], dis: false },
    { name: '钟琪钰', alias: 'ccc', code: 333, select: [111], dis: false },
    { name: '曦曦', alias: 'ddd', code: 444, select: [111], dis: true },
    { name: '色伟', alias: 'eee', code: 555, select: [111], dis: true },
  ]

  const sRef = useRef(null)
  const cRef = useRef(null)

  useEffect(() => {
    // console.log('###: ------- ', sRef.current);

    // console.log('###: -------ccccccccccccc ', cRef.current);
  }, [])




  const getData = (params: any, searchValue?: string): Promise<Array<Ilist>> => {
    console.log(`###:  请求参数：${params}，搜索值：${searchValue}`);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(creactList(searchValue))
      }, 1000)
    })
  }

  console.log('###:  父组件----------------',);

  const [_, setRender] = useState({});


  const aa = useRef<any>(null);
  const listd = useRef([]);




  const newList: any = useMemo(() => {
    const arr = new Array(5).fill(0).map((item, index) => {
      const a = Math.random().toFixed(3)
      return {
        name: `你好 ${index}`,
        alias: `aaa ${a}`,
        code: index,
        select: [111],
      }
    })

    return arr
  }, [])
  const [listData, setListData] = useState<Array<Ilist>>([]);
  useEffect(() => {
    setTimeout(() => {
      setListData(newList)
    }, 1000)
  }, [])

  useEffect(() => {
    console.log('###:  render-------------------',);
  }, [list])

  const [form] = Form.useForm();

  return (
    <div>
      <button onClick={() => {
        setRender({})
        console.log('###:  ffffffff', form.getFieldsValue());
        // aa.current.setFieldsValue({
        //   1: 6666666666
        // })

        console.log('###:  list-------', listd.current, listData);
      }}>render</button>

      <button onClick={() => {
        console.log('###:  ', form.getFieldValue('demo'));
      }}>获取数据</button>

      <CSelect
        // enableLocalSearch
        createRef={cRef}
        dataSource={list}
        ownKey={(item) => {
          return item.name!
        }}
        params={form.getFieldValue('demo')}
        // request={getData}
        // disabledOption={[1]}
        // disabledField='code'
        disabledField='code'
        handleDisabled={(value) => {
          return value === 60
        }}
        // disabledOption={[11, 22]}
        value={[111, 5]}
        // mode='tags'
        mode='multiple'
        // errorHint
        // formatDataSource={(data) => {
        //   console.log('###:  1111111', data.list);
        //   return data.list
        // }}
        // initialDefaultData={[
        //   { name: 'aa', code: 1111111, },
        //   { name: 'bb', code: 2222222, },
        //   { name: 'cc', code: 3333333, },
        // ]}
        // value={11}
        // maxCount={3}
        handleChange={(value, target, option) => {
          console.log('###: handle---- ', value, target, option,);
        }}
      // extendFilterOption={(item) => {
      //   console.log('###:  ', item);
      //   return item.name.includes('6')
      // }}
      />

      <Form form={form}>
        <Form.Item
          name='demo'
          // initialValue={[11, 5, 88]}
          initialValue={11}
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <CSelect
            // enableLocalSearch
            createRef={cRef}
            dataSource={list}
            request={getData}
            // disabledOption={[1]}
            // disabledField='code'
            disabledField='code'
            handleDisabled={(value) => {
              return value === 60
            }}
            disabledOption={[11, 22]}
            // value={[1, 5]}
            // mode='tags'
            // mode='multiple'
            // errorHint
            // formatDataSource={(data) => {
            //   console.log('###:  1111111', data.list);
            //   return data.list
            // }}
            initialDefaultData={[
              { name: 'aa', code: 11, },
              { name: 'bb', code: 22, },
              { name: 'cc', code: 33, },
            ]}
            // value={11}
            // maxCount={3}
            handleChange={(value, target, option) => {
              console.log('###: handle---- ', value, target, option,);
            }}
          // extendFilterOption={(item) => {
          //   console.log('###:  ', item);
          //   return item.name.includes('6')
          // }}
          />
        </Form.Item>
      </Form>




      <button onClick={() => {
        console.log('###:  ', form.getFieldValue('ccc'));
      }}>获取数据</button>
      <Form form={form}>
        <Form.Item
          name='ccc'
        // initialValue={[11, 5, 80, 74]}
        >
          <Select
            ref={sRef}
            allowClear
            showSearch
            style={{
              minWidth: 140,
              width: '100%',
            }}
            mode='tags'
          >
            {list.map((target: any) => {
              const { name, code } = target;

              return (
                <Select.Option
                  key={code}
                  value={code}
                  title={name}
                  __tag={target}
                >
                  {name}
                </Select.Option>
              );
            })}
          </Select>

        </Form.Item>
      </Form>




























      <ModalWrapper
        forceRender
        title={<h1>12</h1>}
        render={(a, b) => {
          return (
            <Form
              form={a.form}
              name='basic'
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 16 }}
              initialValues={{ remember: true }}
              autoComplete='off'
            >
              <Form.Item
                label='Username'
                name='username'
                rules={[
                  {
                    required: true,
                    max: 10,
                    message: '用户名最大10位',
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Form>
          )
        }}
      >
        你好666
      </ModalWrapper>


      <button onClick={() => {
        modalRef.current && modalRef.current.show(true, {
          id: 6666,
          name: '台风来了'
        }, {
          title: `132222【${a}】`
        })
      }}>弹框提交</button>

      <button onClick={() => {
        drawerRef.current && drawerRef.current.show(true, {
          id: 6666,
          name: '台风来了'
        }, {
          closable: false,
          title: 123,
        })
      }}>抽屉提交</button>






      <DrawerWrapper
        title='你好'
        width='80%'
        // footType='onlyClose'
        // customFooter={null}
        modalRef={(ref) => {
          drawerRef.current = ref
        }}
        onShow={(a, b, c) => {

        }}
        render={(a, b) => {
          return (
            <Form form={a.form}>
              <AgGroup
                style={{
                  width: 900
                }}
                // initValue={{
                //   name: '测试',
                //   code: 111,
                //   select: [111],
                //   dis: true
                // }}
                // keyName='code'
                // min={3}
                dataSource={listData}
                render={(target, id, fun) => {

                  return (
                    <div style={{
                      display: 'flex',
                      width: '100%',
                      justifyContent: 'space-around',
                    }}>
                      <div style={{ margin: '5px' }} >
                        <Form.Item
                          name={`${id}-name`}
                          label="Username"
                          rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                          <Input
                            value={target.name}
                            onChange={(e) => {
                              fun.notify(id, (item) => {
                                item.name = e.target.value
                              })
                            }}
                          />
                        </Form.Item>
                      </div>
                      <div style={{ margin: '5px' }} >
                        <Input
                          value={target.alias}
                          onChange={(e) => {
                            fun.notify(id, (item) => {
                              item.alias = e.target.value
                            })
                          }}
                        />
                      </div>
                      <div style={{ margin: '5px' }} >
                        <Form.Item
                          name={`${id}-select`}
                          label="选择"
                          rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                          <CSelect
                            mode='multiple'
                            value={target.select}
                            dataSource={datalist}
                            onChange={() => { }}
                            handleChange={(value: any) => {
                              fun.notify(id, (item) => {
                                item.select = value
                                item.alias = value
                              })
                            }}
                          />
                        </Form.Item>
                      </div>
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          paddingBottom: 5,
                          width: 150,
                          height: 50
                        }}
                      >
                        <button
                          onClick={() => {
                            fun.add(id)
                          }}
                        >新增</button>
                        <button
                          onClick={() => {
                            fun.remove(id)
                          }}
                        >删除</button>
                      </div>
                    </div>
                  );
                }}
                getProcessedData={(data: any) => {
                  listd.current = data
                }}
              >
                <div>规则条件</div>
                <div>审批人</div>
                <div>抄送人</div>
                <div></div>
              </AgGroup>
            </Form>
          )
        }}
        submit={(a, b) => {
          console.log('###: ------------ ', a, b);
          return new Promise((a, b) => {
            b()
          })
        }}
      />


      <ModalWrapper
        title='你好'
        width={800}
        modalRef={(ref) => {
          modalRef.current = ref
        }}
        render={(a, b) => {
          const { forwardParams } = a
          return (
            <Demo forwardParams={forwardParams} form={a.form} />
          )
        }}
        submit={(formValue, params, contentParams) => {
          console.log('###:  提交contentParams', formValue, params, contentParams);

          return new Promise((resolve, reject) => {
            reject(1111)

            return false
          })
        }}
      />
    </div>
  );
}

export default App